package com.apply.leetcode.puzzle349_350;

import java.util.ArrayList;
import java.util.TreeSet;

/**
 * 找出2个数组的交集并且不能重复
 * 使用set
 */
public class Solution349 {

    public int[] intersection(int[] num1, int[] num2) {
        TreeSet<Integer> set = new TreeSet<>();
        for (int num: num1) {
            set.add(num);
        }
        ArrayList<Integer> list = new ArrayList<>();
        for (int num: num2) {
            if (set.contains(num)) {
                list.add(num);
                // num2 可能含有set之前已经判断过的元素，故而经过判断的元素要记得重set中删除
                set.remove(num);
            }
        }
        int[] res = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            res[i] = list.get(i);
        }
        return res;
    }
}
